#!/usr/bin/env python
# --*-- coding:utf-8 --*--
# author:g-y-b time:2020/5/25

from PyQt5.QtCore import QTimer, QCoreApplication
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog
from two import Ui_Form
import sys
from sklearn.datasets import load_iris
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import qimage2ndarray
import numpy as np
import csv
import random
import math
import operator
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


def plotImg(X, y, targets, features, title):   # 画图
    """
    利用该数据集特征中的前两个，来展示所有的样本点。
    :param X:数据集
    :param y:数据的label
    :return:
    """
    plt.style.use('ggplot')
    plt.figure(figsize=(10, 4))
    plt.plot(X[:, 0][y == 0], X[:, 1][y == 0], 'bs', label=targets[0])
    plt.plot(X[:, 0][y == 1], X[:, 1][y == 1], 'kx', label=targets[1])
    plt.plot(X[:, 0][y == 2], X[:, 1][y == 2], 'ro', label=targets[2])
    plt.plot(X[:, 0][y == 3], X[:, 1][y == 3], 'rx', label="4")
    plt.xlabel(features[0])
    plt.ylabel(features[1])
    # plt.title('Iris Data Set')
    plt.title(title)
    plt.legend()
    filename = 'Iris Data Set.jpg'
    plt.savefig(filename, dpi=200)
    # plt.show()
    plt.close()


# K_Means
def kmeans(X, k, flag, centroids):
    numPoints, numDim = X.shape
    dataSet = np.zeros((numPoints, numDim + 1))
    dataSet[:, :-1] = X

    if flag == 0:
        centroids = dataSet[np.random.randint(numPoints, size=k), :]
        centroids[:, -1] = range(0, k)
    oldCentroids = np.copy(centroids)

    # 根据聚类中心进行分类
    updateLabels(dataSet, centroids)

    # 更新聚类中心
    centroids = getCentroids(dataSet, k)
    if np.array_equal(oldCentroids, centroids):
        print("聚类中心不再变化，计算结束！")
        return dataSet, centroids, False
    else:
        return dataSet, centroids, True


def updateLabels(dataSet, centroids):
    numPoints, numDim = dataSet.shape
    for i in range(0, numPoints):
        dataSet[i, -1] = getLabelFromClosestCentroid(dataSet[i, :-1], centroids)


def getLabelFromClosestCentroid(dataSetRow, centroids):
    label = centroids[0, -1]
    minDist = np.linalg.norm(dataSetRow - centroids[0, :-1])
    for i in range(1, centroids.shape[0]):
        dist = np.linalg.norm(dataSetRow - centroids[i, :-1])
        if dist < minDist:
            minDist = dist
            label = centroids[i, -1]
    # print("minDist:", minDist)
    return label


def getCentroids(dataSet, k):
    result = np.zeros((k, dataSet.shape[1]))
    for i in range(0, k):
        oneCluster = dataSet[dataSet[:, -1] == i, :-1]
        result[i, :-1] = np.mean(oneCluster, axis=0)
        result[i, -1] = i
    return result


# KNN
def loadDataset(filename, split, trainingSet=[], testSet=[]):
    with open(filename, 'r', encoding='utf-8') as csvfile:
        lines = csv.reader(csvfile)
        dataset = list(lines)
        for x in range(1, len(dataset)):
            # print(x, ':')
            # 只取后两个特征
            dataset[x].pop(0)
            dataset[x].pop(2)
            dataset[x].pop(2)
            if dataset[x][2] == 'setosa':
                dataset[x][2] = 0
            elif dataset[x][2] == 'versicolor':
                dataset[x][2] = 1
            elif dataset[x][2] == 'virginica':
                dataset[x][2] = 2
            for y in range(2):
                dataset[x][y] = float(dataset[x][y])
                # print(dataset[x])
            if random.random() < split:
                trainingSet.append(dataset[x])
            else:
                testSet.append(dataset[x])


def euclideanDistance(instance1, instance2, length):    # 计算欧氏距离
    distance = 0
    for x in range(length):
        distance += pow((instance1[x] - instance2[x]), 2)
    return math.sqrt(distance)


def getNeighbors(traingSet, testInstance, k):     # 返回最近的k个邻居
    distances = []
    length = len(testInstance) - 1
    for x in range(len(traingSet)):
        dist = euclideanDistance(testInstance, traingSet[x], length)
        distances.append((traingSet[x], dist))
    distances.sort(key=operator.itemgetter(1))
    neighbors = []
    for x in range(k):
        neighbors.append(distances[x][0])
    return neighbors


def getResponse(neighbors):     # 进行投票
    classVotes = {}
    for x in range(len(neighbors)):
        response = neighbors[x][-1]
        if response in classVotes:
            classVotes[response] += 1
        else:
            classVotes[response] = 1
    sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)  # 按降序排列
    return sortedVotes[0][0]


class two_ui(QMainWindow, Ui_Form):
    # 在实例化first类时，会自动调用它的初始化函数，因此，我们把想要让程序自动实现的程序功能都放在该函数下
    def __init__(self, parent=None):
        super(two_ui, self).__init__(parent)
        self.setupUi(self)
        self.CallBackFunctions()  # 各个控件背后的功能函数的集合，它定义了我们在程序界面上进行某项操作后实际执行的代码
        # kmeans
        self.num = 0
        self.data = load_iris()
        # 直接读到pandas的数据框中
        pd.DataFrame(data=self.data.data, columns=self.data.feature_names)
        self.X = self.data.data[:, 0:2]  # 只包括样本的特征，150x4,取前两列
        print(self.X.shape)
        self.y = self.data.target  # 样本的类型，[0, 1, 2] 0:setosa 1:versicolor 2:virgincia
        self.features = self.data.feature_names  # 4个特征的名称
        self.targets = self.data.target_names  # 3类鸢尾花的名称，跟y中的3个数字对应
        self.centroids = None
        self.temp = True
        self.newData = np.hstack((self.X, np.zeros((self.X.shape[0], 1))))
        # knn
        self.trainingSet = []
        self.testSet = []
        self.split = 0.67
        self.neighbors = None
        self.prediction = None
        self.nextKnn = 0
        self.pushButton_knn_Next.setEnabled(False)

    def CallBackFunctions(self):
        self.pushButton_kmeans.clicked.connect(self.myKMeans)
        self.pushButton_knn.clicked.connect(self.myKNN)
        self.pushButton_knn_Next.clicked.connect(self.myKNN_Next)
        self.pushButton_Back.clicked.connect(self.dataBack)
        self.pushButton_Back_knn.clicked.connect(self.dataBackKNN)

    def myKMeans(self):
        k = int(self.lineEdit_k.text())
        if k > 4:
            k = 4
        if not self.temp:
            print('次数：' + str(self.num) + '聚类结束！')
            self.label_num.setText('次数：' + str(self.num) + '聚类结束！')
        else:
            self.newData, self.centroids, self.temp = kmeans(self.newData[:, :-1], k, self.num, self.centroids)
            self.y = self.newData[:, -1]
            plotImg(self.newData[:, :-1], self.y, self.targets, self.features, 'Iris Data Set K_means')
            self.showImg()
            self.num += 1
            self.label_num.setText('次数：' + str(self.num))
        print("")

    def dataBack(self):
        self.temp = True
        self.num = 0
        self.centroids = None
        img = cv2.imread('1.jpg')
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # 转RGB
        img = qimage2ndarray.array2qimage(img)  # 数组转QImage
        result = img.scaled(self.label.width(), self.label.height())
        self.label.setPixmap(QPixmap.fromImage(result))
        self.label.show()

    def myKNN(self):
        self.trainingSet = []
        self.testSet = []
        loadDataset('iris.csv', self.split, self.trainingSet, self.testSet)
        print('Train set:', repr(len(self.trainingSet)))
        print('Test set:', repr(len(self.testSet)))
        self.pushButton_knn_Next.setEnabled(True)
        plotImg(np.array(self.trainingSet)[:, :-1], np.array(self.trainingSet)[:, -1],
                self.targets, self.features, 'Iris Data Set KNN')
        self.showImg()

        # 随机选取测试集中的一个点
        flag = random.randint(0, len(self.testSet))
        self.prediction = self.testSet[flag]
        k = int(self.lineEdit_knn.text())
        self.neighbors = getNeighbors(self.trainingSet, self.prediction, k)
        print(self.neighbors)
        self.pushButton_knn_Next.setEnabled(True)

    def myKNN_Next(self):
        if self.nextKnn == 0:
            X = np.array(self.trainingSet)[:, :-1]
            y = np.array(self.trainingSet)[:, -1]
            plt.style.use('ggplot')
            plt.figure(figsize=(10, 4))
            print(self.prediction)
            plt.plot(X[:, 0][y == 0], X[:, 1][y == 0], 'bs', label=self.targets[0])
            plt.plot(X[:, 0][y == 1], X[:, 1][y == 1], 'kx', label=self.targets[1])
            plt.plot(X[:, 0][y == 2], X[:, 1][y == 2], 'ro', label=self.targets[2])
            plt.plot(self.prediction[0], self.prediction[1], 'kD', label=u'待分类的点')
            plt.plot(np.array(self.neighbors)[:, 0], np.array(self.neighbors)[:, 1],
                     'y2', label=u"最近的已知实例")
            plt.xlabel(self.features[0])
            plt.ylabel(self.features[1])
            plt.title('Iris Data Set KNN')
            plt.legend()
            filename = 'Iris Data Set.jpg'
            plt.savefig(filename, dpi=200)
            # plt.show()
            plt.close()
            self.showImg()
            self.nextKnn = 1
        elif self.nextKnn == 1:
            result = getResponse(self.neighbors)
            flowerType = ''
            if result == 0:
                flowerType = 'setosa'
            elif result == 1:
                flowerType = 'versicolor'
            elif result == 2:
                flowerType = 'virginica'
            self.label_knn_result.setText("类别为：" + flowerType)

    def dataBackKNN(self):
        self.pushButton_knn_Next.setEnabled(False)
        self.nextKnn = 0
        self.neighbors = None
        self.trainingSet = []
        self.prediction = None
        img = cv2.imread('1.jpg')
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # 转RGB
        img = qimage2ndarray.array2qimage(img)  # 数组转QImage
        result = img.scaled(self.label.width(), self.label.height())
        self.label.setPixmap(QPixmap.fromImage(result))
        self.label.show()
        self.label_knn_result.setText("类别为：")

    def showImg(self):
        img = cv2.imread('Iris Data Set.jpg')
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # 转RGB
        img = qimage2ndarray.array2qimage(img)  # 数组转QImage
        # 使图片适应label大小
        result = img.scaled(self.label.width(), self.label.height())
        self.label.setPixmap(QPixmap.fromImage(result))
        self.label.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = two_ui()
    ui.show()
    sys.exit(app.exec_())
